<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-11-13
 * Time: 17:43
 */

namespace app\index\controller;

use app\src\base\helper\ValidateHelper;
use app\src\hook\PaySuccessHook;
use app\src\order\enum\PayType;
use app\src\order\logic\OrdersPaycodeLogic;
use app\src\order\model\OrdersPaycode;
use think\Controller;

/**
 * Paypal
 * Class Paypal
 * @author hebidu <email:346551990@qq.com>
 * @package app\index\controller
 */
class Paypal extends Controller{

    public function index(){
        $input = file_get_contents("php://input");

        addLog("Paypal_notify",$input,$_POST,"Paypal异步通知input");
        $obj = json_decode($input,JSON_OBJECT_AS_ARRAY);
        $event_type = isset($obj['event_type']) ? $obj['event_type']:"";
        $resource_type = isset($obj['resource_type']) ? $obj["resource_type"] : "";
        $resource = isset($obj['resource']) ? $obj["resource"] : "";

        $amount = isset($resource['amount']) ? $resource["amount"] : "";
        $trade_no =  isset($resource['id']) ? $resource["id"] : "";

        $total = isset($amount['total']) ? $amount["total"] : "";
        $currency = isset($amount['currency']) ? $amount["currency"] : "";

        addLog("Paypal_notify",$obj,$resource,"Paypal异步通知");
        if($resource_type == "sale" && $event_type == "PAYMENT.SALE.COMPLETED"){

            addLog("Paypal_notify".$total.$currency,$obj,$resource,"Paypal交易完成异步通知");

            $result = (new OrdersPaycodeLogic())->getInfo(['trade_no'=>$trade_no]);

            if(ValidateHelper::legalArrayResult($result)){
                $payInfo = $result['info'];
                $result = (new PaySuccessHook())->success("",$total,$payInfo['pay_code'],$currency,$trade_no,PayType::PAYPAL);
                
                if($result['status']){
                    echo $result['info'];
                    return ;
                }
            }
        }

        echo "ok";
    }

}